<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>数据库产品管理 - H5版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 100%;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            min-height: 100vh;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }

        .header {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .header p {
            font-size: 14px;
            opacity: 0.9;
        }

        .search-bar {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #eee;
        }

        .search-input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            border-color: #4CAF50;
            box-shadow: 0 0 10px rgba(76, 175, 80, 0.2);
        }

        .list-container {
            position: relative;
            overflow: hidden;
        }

        .pull-to-refresh {
            position: absolute;
            top: -60px;
            left: 50%;
            transform: translateX(-50%);
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 14px;
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .product-list {
            padding: 0;
            margin: 0;
            list-style: none;
        }

        .product-item {
            background: white;
            margin: 10px 20px;
            border-radius: 15px;
            box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            transition: all 0.3s ease;
            animation: fadeInUp 0.5s ease;
        }

        .product-item:active {
            transform: scale(0.98);
            box-shadow: 0 1px 8px rgba(0, 0, 0, 0.15);
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .product-content {
            display: flex;
            padding: 20px;
            align-items: center;
        }

        .product-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            overflow: hidden;
        }

        .product-icon img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            border-radius: 12px;
        }

        .product-info {
            flex: 1;
        }

        .product-name {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .product-type {
            font-size: 12px;
            color: #4CAF50;
            background: rgba(76, 175, 80, 0.1);
            padding: 3px 8px;
            border-radius: 10px;
            display: inline-block;
            margin-bottom: 8px;
        }

        .product-description {
            font-size: 14px;
            color: #666;
            line-height: 1.4;
        }

        .loading-more {
            text-align: center;
            padding: 20px;
            color: #999;
            font-size: 14px;
        }

        .loading-more.show {
            display: block;
        }

        .loading-more.hide {
            display: none;
        }

        /* 电脑端专用样式 */
        .computer-load-more {
            display: none;
            text-align: center;
            padding: 30px 20px;
            margin: 20px;
            border: 2px dashed #ddd;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.5);
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .computer-load-more:hover {
            border-color: #4CAF50;
            background: rgba(76, 175, 80, 0.1);
            transform: translateY(-2px);
        }

        .computer-load-more.show {
            display: block;
        }

        .computer-load-more .icon {
            font-size: 24px;
            margin-bottom: 8px;
            color: #4CAF50;
        }

        .computer-load-more .text {
            color: #666;
            font-size: 16px;
            margin-bottom: 4px;
        }

        .computer-load-more .hint {
            color: #999;
            font-size: 12px;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #4CAF50;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .no-data {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .no-data img {
            width: 80px;
            height: 80px;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .error-message {
            text-align: center;
            padding: 20px;
            color: #f44336;
            background: rgba(244, 67, 54, 0.1);
            margin: 10px 20px;
            border-radius: 10px;
            border-left: 4px solid #f44336;
        }

        /* 下拉刷新动画 */
        .refreshing {
            animation: bounce 0.6s ease;
        }

        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% {
                transform: translateY(0);
            }
            40% {
                transform: translateY(-10px);
            }
            60% {
                transform: translateY(-5px);
            }
        }

        /* 响应式设计 */
        @media (max-width: 480px) {
            .container {
                margin: 0;
                border-radius: 0;
            }
            
            .product-item {
                margin: 8px 15px;
            }
            
            .product-content {
                padding: 15px;
            }
            
            .product-icon {
                width: 50px;
                height: 50px;
            }
            
            .product-name {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 数据库产品管理</h1>
            <p id="deviceSupportText">移动端产品展示页面</p>
        </div>

        <div class="search-bar">
            <input type="text" class="search-input" placeholder="🔍 搜索产品名称..." id="searchInput">
        </div>

        <div class="list-container" id="listContainer">
            <div class="pull-to-refresh" id="pullToRefresh">下拉刷新</div>
            
            <ul class="product-list" id="productList">
                <!-- 产品列表项将动态生成 -->
            </ul>

            <div class="loading-more hide" id="loadingMore">
                <div class="loading-spinner"></div>
                加载中...
            </div>

            <!-- 电脑端加载更多按钮 -->
            <div class="computer-load-more" id="computerLoadMore" onclick="loadMoreProducts()">
                <div class="icon">⬇️</div>
                <div class="text">加载更多产品</div>
                <div class="hint">点击加载更多数据</div>
            </div>
        </div>

        <div class="no-data" id="noData" style="display: none;">
            <div style="font-size: 48px; margin-bottom: 20px;">📱</div>
            <div>暂无数据</div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let isLoading = false;
        let hasMore = true;
        let allProducts = [];
        let filteredProducts = [];
        let startY = 0;
        let isRefreshing = false;
        let mouseStartY = 0;
        let isMouseDown = false;
        let mouseStartX = 0;
        
        // 设备检测
        let isMobileDevice = window.innerWidth <= 768 || /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

        // API配置
        const API_BASE_URL = 'http://localhost/dev-api';
        // 支持多种图片路径格式的base URL
        const IMAGE_BASE_URL = 'http://localhost/dev-api/profile/upload/';
        // 默认图标SVG (base64编码)
        const DEFAULT_ICON = '';

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateDeviceSupportText();
            initEventListeners();
            loadProducts(true);
        });

        // 更新设备支持文字
        function updateDeviceSupportText() {
            const deviceSupportText = document.getElementById('deviceSupportText');
            const computerLoadMore = document.getElementById('computerLoadMore');
            const loadingMore = document.getElementById('loadingMore');
            
            if (isMobileDevice) {
                deviceSupportText.textContent = '移动端产品展示页面';
                computerLoadMore.style.display = 'none';
                loadingMore.style.display = 'block';
            } else {
                deviceSupportText.textContent = '电脑端产品展示页面 - 支持下拉刷新和点击加载更多';
                computerLoadMore.style.display = 'block';
                loadingMore.style.display = 'none';
            }
        }

        // 初始化事件监听器
        function initEventListeners() {
            const listContainer = document.getElementById('listContainer');
            const searchInput = document.getElementById('searchInput');

            // 下拉刷新 - 触摸事件
            listContainer.addEventListener('touchstart', handleTouchStart, { passive: true });
            listContainer.addEventListener('touchmove', handleTouchMove, { passive: true });
            listContainer.addEventListener('touchend', handleTouchEnd, { passive: true });

            // 下拉刷新 - 鼠标事件（电脑端）
            listContainer.addEventListener('mousedown', handleMouseDown, { passive: false });
            listContainer.addEventListener('mousemove', handleMouseMove, { passive: false });
            listContainer.addEventListener('mouseup', handleMouseUp, { passive: false });
            listContainer.addEventListener('mouseleave', handleMouseUp, { passive: false });

            // 搜索功能
            let searchTimeout;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    filterProducts(this.value);
                }, 300);
            });

            // 滚动加载
            window.addEventListener('scroll', handleScroll, { passive: true });
        }

        // 处理触摸开始
        function handleTouchStart(e) {
            startY = e.touches[0].clientY;
        }

        // 处理触摸移动
        function handleTouchMove(e) {
            if (isLoading || isRefreshing) return;
            
            const currentY = e.touches[0].clientY;
            const diffY = currentY - startY;
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            // 下拉刷新逻辑
            if (scrollTop === 0 && diffY > 50) {
                e.preventDefault();
                showPullToRefresh();
            }
        }

        // 处理触摸结束
        function handleTouchEnd(e) {
            const pullToRefresh = document.getElementById('pullToRefresh');
            if (pullToRefresh.style.top === '60px') {
                startRefresh();
            }
            hidePullToRefresh();
        }

        // 处理鼠标按下
        function handleMouseDown(e) {
            mouseStartY = e.clientY;
            mouseStartX = e.clientX;
            isMouseDown = true;
        }

        // 处理鼠标移动
        function handleMouseMove(e) {
            if (!isMouseDown || isLoading || isRefreshing) return;
            
            const currentY = e.clientY;
            const currentX = e.clientX;
            const diffY = currentY - mouseStartY;
            const diffX = currentX - mouseStartX;
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            // 检查是否为向下拖拽（垂直方向）且在顶部
            if (diffY > 50 && Math.abs(diffY) > Math.abs(diffX) && scrollTop === 0) {
                e.preventDefault();
                showPullToRefresh();
            }
        }

        // 处理鼠标释放
        function handleMouseUp(e) {
            if (!isMouseDown) return;
            
            isMouseDown = false;
            const pullToRefresh = document.getElementById('pullToRefresh');
            
            if (pullToRefresh.style.top === '60px') {
                startRefresh();
            }
            hidePullToRefresh();
        }

        // 显示下拉刷新提示
        function showPullToRefresh() {
            const pullToRefresh = document.getElementById('pullToRefresh');
            pullToRefresh.style.top = '60px';
            pullToRefresh.textContent = '松开刷新';
        }

        // 隐藏下拉刷新提示
        function hidePullToRefresh() {
            const pullToRefresh = document.getElementById('pullToRefresh');
            pullToRefresh.style.top = '-60px';
            pullToRefresh.textContent = '下拉刷新';
        }

        // 开始刷新
        function startRefresh() {
            if (isRefreshing) return;
            isRefreshing = true;
            loadProducts(true);
        }

        // 处理滚动事件
        function handleScroll() {
            if (isLoading || !hasMore || isMobileDevice) return; // 电脑端不自动加载
            
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const windowHeight = window.innerHeight;
            const documentHeight = document.documentElement.scrollHeight;
            
            // 电脑端不自动加载，只显示加载更多按钮
            // 移动端：滚动到底部前100px开始加载
            if (!isMobileDevice) {
                showComputerLoadMore();
            } else if (scrollTop + windowHeight >= documentHeight - 100) {
                loadMoreProducts();
            }
        }

        // 显示电脑端加载更多按钮
        function showComputerLoadMore() {
            const computerLoadMore = document.getElementById('computerLoadMore');
            const loadingMore = document.getElementById('loadingMore');
            
            if (hasMore && !isLoading) {
                computerLoadMore.classList.add('show');
                loadingMore.classList.remove('show');
            } else {
                computerLoadMore.classList.remove('show');
            }
        }

        // 隐藏电脑端加载更多按钮
        function hideComputerLoadMore() {
            const computerLoadMore = document.getElementById('computerLoadMore');
            computerLoadMore.classList.remove('show');
        }

        // 加载产品列表
        async function loadProducts(isRefresh = false) {
            if (isLoading) return;
            
            isLoading = true;
            showLoading(true);

            try {
                const response = await fetch(`${API_BASE_URL}/system/product/list?pageNum=${currentPage}&pageSize=${pageSize}`);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.code === 200 && data.rows) {
                    if (isRefresh) {
                        allProducts = [...data.rows];
                        currentPage = 1;
                    } else {
                        allProducts = [...allProducts, ...data.rows];
                    }
                    
                    filteredProducts = [...allProducts];
                    renderProducts();
                    hasMore = data.rows.length === pageSize;
                    
                    // 加载完成后更新加载更多按钮显示
                    setTimeout(() => {
                        if (isMobileDevice) {
                            hideComputerLoadMore();
                        } else {
                            showComputerLoadMore();
                        }
                    }, 100);
                    
                    if (isRefresh) {
                        isRefreshing = false;
                        // 添加刷新动画
                        document.getElementById('listContainer').classList.add('refreshing');
                        setTimeout(() => {
                            document.getElementById('listContainer').classList.remove('refreshing');
                        }, 600);
                    }
                } else {
                    throw new Error(data.msg || '获取数据失败');
                }
            } catch (error) {
                console.error('加载产品失败:', error);
                showError('加载失败: ' + error.message);
            } finally {
                isLoading = false;
                showLoading(false);
            }
        }

        // 加载更多产品
        function loadMoreProducts() {
            if (!hasMore || isLoading) return;
            
            currentPage++;
            loadProducts(false);
        }

        // 过滤产品
        function filterProducts(searchTerm) {
            const term = searchTerm.toLowerCase().trim();
            
            if (!term) {
                filteredProducts = [...allProducts];
            } else {
                filteredProducts = allProducts.filter(product => 
                    product.databaseName.toLowerCase().includes(term) ||
                    product.dbType.toLowerCase().includes(term) ||
                    (product.description && product.description.toLowerCase().includes(term))
                );
            }
            
            renderProducts();
        }

        // 构建图片URL的函数
        function buildImageUrl(iconPath) {
            if (!iconPath || iconPath === '#' || iconPath.trim() === '') {
                return DEFAULT_ICON;
            }
            
            // 如果已经是完整URL，直接返回
            if (iconPath.startsWith('http://') || iconPath.startsWith('https://')) {
                return iconPath;
            }
            
            // 如果以/profile/upload/开头，说明是相对路径，添加/dev-api代理前缀
            if (iconPath.startsWith('/profile/upload/')) {
                return `http://localhost/dev-api${iconPath}`;
            }
            
            // 如果以profile/upload/开头（没有斜杠），添加/dev-api代理前缀
            if (iconPath.startsWith('profile/upload/')) {
                return `http://localhost/dev-api/${iconPath}`;
            }
            
            // 如果不包含路径分隔符，说明只有文件名，添加到base URL后面
            if (!iconPath.includes('/')) {
                return `${IMAGE_BASE_URL}${iconPath}`;
            }
            
            // 其他情况直接返回
            return iconPath;
        }

        // 渲染产品列表
        function renderProducts() {
            const productList = document.getElementById('productList');
            const noData = document.getElementById('noData');
            
            if (filteredProducts.length === 0) {
                productList.innerHTML = '';
                noData.style.display = 'block';
                return;
            }
            
            noData.style.display = 'none';
            
            productList.innerHTML = filteredProducts.map(product => {
                const iconUrl = buildImageUrl(product.icon);
                
                return `
                    <li class="product-item" onclick="showProductDetail(${product.productId})">
                        <div class="product-content">
                            <div class="product-icon">
                                <img src="${iconUrl}" alt="${product.databaseName}" onerror="this.src='${DEFAULT_ICON}';">
                            </div>
                            <div class="product-info">
                                <div class="product-name">${product.databaseName}</div>
                                <div class="product-type">${product.dbType}</div>
                                <div class="product-description">${product.description || '暂无描述'}</div>
                            </div>
                        </div>
                    </li>
                `;
            }).join('');
        }

        // 显示产品详情
        function showProductDetail(productId) {
            const product = allProducts.find(p => p.productId === productId);
            if (!product) return;

            const iconUrl = buildImageUrl(product.icon);

            const detailHtml = `
                <div style="
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.8);
                    z-index: 10000;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                " onclick="this.remove()">
                    <div style="
                        background: white;
                        border-radius: 20px;
                        padding: 30px;
                        max-width: 400px;
                        width: 100%;
                        position: relative;
                    " onclick="event.stopPropagation()">
                        <button onclick="this.closest('div[style*=fixed]').remove()" style="
                            position: absolute;
                            top: 15px;
                            right: 15px;
                            background: #f44336;
                            color: white;
                            border: none;
                            border-radius: 50%;
                            width: 30px;
                            height: 30px;
                            cursor: pointer;
                            font-size: 18px;
                        ">×</button>
                        
                        <div style="text-align: center; margin-bottom: 20px;">
                            <img src="${iconUrl}" alt="${product.databaseName}" style="
                                width: 80px;
                                height: 80px;
                                border-radius: 15px;
                                object-fit: contain;
                            " onerror="this.src='${DEFAULT_ICON}';">
                        </div>
                        
                        <h2 style="margin: 0 0 15px 0; color: #333; text-align: center;">${product.databaseName}</h2>
                        
                        <div style="
                            background: rgba(76, 175, 80, 0.1);
                            color: #4CAF50;
                            padding: 8px 15px;
                            border-radius: 20px;
                            text-align: center;
                            margin-bottom: 20px;
                            font-size: 14px;
                        ">${product.dbType}</div>
                        
                        <div style="color: #666; line-height: 1.6;">
                            <strong>产品描述：</strong><br>
                            ${product.description || '暂无描述'}
                        </div>
                        
                        ${product.remark ? `
                            <div style="color: #666; line-height: 1.6; margin-top: 15px;">
                                <strong>备注信息：</strong><br>
                                ${product.remark}
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', detailHtml);
        }

        // 显示/隐藏加载状态
        function showLoading(show) {
            const loadingMore = document.getElementById('loadingMore');
            if (show) {
                loadingMore.classList.remove('hide');
                loadingMore.classList.add('show');
            } else {
                loadingMore.classList.remove('show');
                loadingMore.classList.add('hide');
            }
        }

        // 显示错误信息
        function showError(message) {
            // 移除之前的错误信息
            const existingError = document.querySelector('.error-message');
            if (existingError) {
                existingError.remove();
            }

            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = message;
            
            const listContainer = document.getElementById('listContainer');
            listContainer.insertBefore(errorDiv, listContainer.firstChild);
            
            // 3秒后自动移除错误信息
            setTimeout(() => {
                if (errorDiv.parentNode) {
                    errorDiv.remove();
                }
            }, 3000);
        }
    </script>
</body>
</html>